package org.example.algorithm.array;

import java.util.*;

public class SectionMergeSolution {

    //输入：intervals = [[1,3],[2,6],[8,10],[15,18]]
    //输出：[[1,6],[8,10],[15,18]]
    //解释：区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
    //先排序，再做一次遍历
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> ans = new ArrayList<>();
        for (int i=0;i<intervals.length;i++) {
            int left = intervals[i][0];
            int right = intervals[i][1];
            if (i == 0 || left > ans.get(ans.size()-1)[1]) {
                ans.add(new int[]{left, right});
            } else {
                ans.get(ans.size()-1)[1] = Math.max(right, ans.get(ans.size()-1)[1]);
            }
        }
        return ans.toArray(new int[ans.size()][]);
    }

}
